package com.huang.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.auth.constants.UserWrapperConstant;
import com.huang.auth.dao.AuthUserDao;
import com.huang.auth.entity.po.AuthRolePO;
import com.huang.auth.entity.po.AuthUserPO;
import com.huang.auth.entity.to.CreatTokenTO;
import com.huang.auth.entity.to.TokenInfoTO;
import com.huang.auth.service.AuthTokenService;
import com.huang.utils.JWTTokenUtil;
import com.huang.utils.entity.to.TokenValResultTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author HuangShen
 * @Description
 * @create 2021-10-04 15:05
 */
@Service(value = "authTokenService")
public class AuthTokenServiceImpl implements AuthTokenService {


    @Value("${com.huang.auth.jwt.secret:45112879655224447755513037744120}")
    private String JWTSecret;
    @Value("${com.huang.auth.jwt.expires:3}")
    private Long tokenExpiresIn;

    @Resource
    private AuthUserDao authUserDao;


    /**
     * 验证 token
     *
     * @param token token
     * @return hashmap
     */
    @Override
    public TokenValResultTO validationToken(String token) {
        return JWTTokenUtil.validationToken(token, JWTSecret);
    }

    /**
     * 生成token
     *
     * @param authUserAccount 用户 账号
     * @return hashmap
     */
    @Override
    public CreatTokenTO creatToken(String authUserAccount) {

        QueryWrapper<AuthUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(UserWrapperConstant.ACCOUNT, authUserAccount);
        AuthUserPO authUserPO = this.authUserDao.selectOne(queryWrapper);
        if (Objects.isNull(authUserPO)) {
            return null;
        }
        // 获取角色信息
        List<AuthRolePO> authRolePOS = this.authUserDao.queryRoleById(authUserPO.getId());

        TokenInfoTO tokenInfoTO = new TokenInfoTO();
        tokenInfoTO.setUserAccount(authUserPO.getAccount());
        tokenInfoTO.setUserId(authUserPO.getId());
        authRolePOS.forEach(authRolePO -> tokenInfoTO.getRoleNames().add(authRolePO.getName()));
        // 生成token
        String token = JWTTokenUtil.creatToken(JSON.toJSONString(tokenInfoTO), JWTSecret, tokenExpiresIn);
        String refreshToken = JWTTokenUtil.creatToken(JSON.toJSONString(tokenInfoTO), JWTSecret, tokenExpiresIn + 2);
        CreatTokenTO creatTokenTO = new CreatTokenTO();
        creatTokenTO.setToken(token);
        creatTokenTO.setRefreshToken(refreshToken);
        creatTokenTO.setExpires_in(tokenExpiresIn * 3600);
        return creatTokenTO;
    }


}
